package com.littcore.saap.assistant.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.littcore.saap.assistant.dao.TagAssocDao;
import com.littcore.saap.assistant.dao.TagDao;
import com.littcore.saap.assistant.po.Tag;
import com.littcore.saap.assistant.po.TagAssoc;
import com.littcore.saap.assistant.service.ITagService;
import com.littcore.saap.core.web.util.LoginUtils;
import com.littcore.util.MyCollectionUtils;

/**
 * .
 * 
 * <pre>
 * <b>描述：</b>
 * 
 * </pre>
 * 
 * <pre>
 * <b>修改记录：</b>
 * 
 * </pre>
 * 
 * @author <a href="mailto:littcai@hotmail.com">蔡源</a>
 * @since 2015年7月1日
 * @version 1.0
 */
public class TagServiceImpl implements ITagService {

	@Resource
	private TagDao tagDao;
	@Resource
	private TagAssocDao tagAssocDao;

	@Override
	public void saveTag(Tag tag, int recordId) {
		tag.setCreateDatetime(new Date());
		int tagId = tagDao.save(tag);
		TagAssoc assoc = new TagAssoc();
		assoc.setRecordId(recordId);
		assoc.setTagId(tagId);
		assoc.setTenantId(tag.getTenantId());
		tagAssocDao.save(assoc);

	}

	@Override
	public List getTags(int tenantId, String moduleCode, int recordId) {
       String hql="select new map(tag as tag,assoc as assoc) from Tag  tag,TagAssoc  assoc where assoc.recordId=? and tag.moduleCode=? and tag.id=assoc.tagId and tag.tenantId=?";
       List tagsDb= tagDao.listAll(hql, new Object[]{recordId,moduleCode,tenantId});
       if(MyCollectionUtils.isEmpty(tagsDb)){
    	   return new ArrayList<Object>();
       }else{
    	   return tagsDb;
       }

	}

	@Override
	public void deleteTag(int tagId) {
		Tag tag=tagDao.load(tagId);
		// 校验租户权限
		LoginUtils.validateTenant(tag.getTenantId());
		
		String hql="delete from TagAssoc where tagId=?";
		tagAssocDao.execute(hql,new Object[]{tagId});
		
	}

}
